<template>
  <div class="app-container">
    <div class="filter-container">
      <p style="float:left;margin-top:5px;margin-left:2%">发布状态：</p>
      <el-select
        size="small"
        placeholder="请选择"
        clearable
        class="filter-item"
        style="width: 250px;margin-left:2%"
        v-model="listQuery.status"
      >
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
      </el-select>
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        style="margin-left:3%"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top:1%"
    >
    <el-table-column type="index">
    </el-table-column>
    <el-table-column label="发布内容" min-width="200px" align="center">
      <template slot-scope="scope">
        <!-- <span>{{ scope.row.phoneNumber }}</span> -->
        <span>{{ scope.row.refName }}</span>
      </template>
    </el-table-column>
      <el-table-column label="发布地址" min-width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pubAddr=='firstPage'?'首页':scope.row.pubAddr=='marry'?'易婚庆':scope.row.pubAddr=='job'?'易就业':scope.row.pubAddr=='travel'?'易旅游':scope.row.pubAddr=='edu'?'易教育':scope.row.pubAddr=='special'?'易农特':scope.row.pubAddr=='science'?'易农科':scope.row.pubAddr=='handyService'?'生活服务':scope.row.pubAddr=='profit'?'轻松赚':'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" width="250px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pubTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status=='0'?'已下架':scope.row.status=='1'?'已发布':scope.row.status=='2'?'待发布':'' }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="300px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            size="small"
            align="center"
            type="danger"
            v-if="row.status=='1' || row.status=='2'"
            @click="row.status=='1'?handleChange(row):handleChange1(row)"
          >
            {{row.status=='1'?"下架":row.status=='2'?"上架":""}}
          </el-button>
          <el-button
            size="small"
            align="center"
            type="primary"
            @click="handledelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="150px"
        style="width: 700px; margin-left:50px;"
      >
        <el-form-item label="发布地址：">
          <el-input v-model="temp.pubAddr" :disabled="true"/>
        </el-form-item>
        <el-form-item label="发布时间：">
            <el-radio-group v-model="radio" @change="fabuDate" :disabled="dialogStatus == 'examine' ? true : false">
                <el-radio :label="1">即时发布</el-radio>
                <el-radio :label="2">定时发布：<el-date-picker v-model="temp.pubTime" type="datetime" placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker></el-radio>
            </el-radio-group>
        </el-form-item>
      </el-form>
      <el-form :model="dynamicValidateForm3" style="width: 700px;margin-left:50px" ref="dynamicValidateForm3" class="demo-dynamic">
        <el-form-item
          v-for="(domain, index) in dynamicValidateForm3.domains"
          :label="'专栏内容（岗位）' + index+':'"
          :key="domain.key"
          style="display:flex;"
          >
          <v-selectpage
            :data="sample"
            key-field="id"
            v-model="domain.value"
            show-field="name"
            style="width:400px;float:left;height:40px"
          >
          </v-selectpage>
          <el-button type="warning" style="float:left;margin-top:-3px" @click.prevent="removeDomain3(domain)"><i class="el-icon-remove-outline"></i></el-button>
        </el-form-item>
        <el-form-item>
          <el-button style="margin-left:135px" @click="addDomain3"><i class="el-icon-circle-plus-outline" ></i></el-button>
        </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button
          type="primary"
          @click="createData()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 异步请求 delLly

import { getListPage,delBottom,getPubList,addBottom,updateStatus,updateUp } from '@/api/bottomContent'
import Vue from 'vue'
import {addImg} from '@/api/headWheel'
// import { addImg,getAllProInfo,updateHead,addBottom} from '@/api/headWheel'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // 分页插件
import { SelectPage } from 'v-selectpage'

const calendarTypeOptions = [
  { key: '0', display_name: '已下架' },
  { key: '1', display_name: '已发布' },
  { key: '2', display_name: '待发布' },
]
const channelTypeOptions = [
  { key: 'APPLETS', display_name: '小程序' },
  { key: 'CUSTOMER_APP', display_name: 'C端APP' },
  { key: 'SHOP_KEEPER', display_name: '掌柜APP' },
  { key: 'OPERATE', display_name: '运营管理平台' }
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
const channelTypeKeyValue = channelTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  inject:["reload"],
  components: { Pagination ,'v-selectpage': SelectPage},

  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
    channelTypeFilter(type) {
      return channelTypeKeyValue[type]
    }
  },
  data() {
    return {
      radio:1,
      sample: [
      ],
      dynamicValidateForm3: {
        domains: [{
          value: '',
        }],
      },
      refId:[],
      channelTypeOptions,
      deptValue:'',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 0,
        pageSize: 10,
        status:'',
        sort: '+id',
      },
      deps:[],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        imgUrl: '',
      },
      dialogFormVisible: false,
      calendarTypeOptions,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
        examine: '查看详情'
      },
      rowId:"",
      dialogPvVisible: false,
      outerVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      liaUser: null,
      ids:[],
      select:null,
      allInfo:[]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    fabuDate(){
        console.log(this.radio)
        if(this.radio===1){
            this.temp.pubTime=null
        }else if(this.radio===2){
            return this.temp.pubTime
        }
    },
    handleAvatarSuccess(res, file) {
        this.temp.imgUrl = URL.createObjectURL(file.raw);
    },
    customRequest (data) {
      const formData = new FormData()
      formData.append('file', data.file)
      this.saveFile(formData)
    },
    saveFile (formData) {
      addImg(formData).then(res=>{
        // this.imageUrl=res.data
        this.temp.imgUrl=res.data.filePath
        console.log(this.temp.imgUrl)
      })
    },
    removeDomain3(item) {
      var index = this.dynamicValidateForm3.domains.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm3.domains.splice(index, 1)
      }
    },
    addDomain3() {
      this.dynamicValidateForm3.domains.push({
        value: '',
        key: Date.now()
      });
    },
    getList() {
      this.listLoading = true
      var params = {
        // pageConvert: true,
        pageNum: this.listQuery.pageNum,
        pageSize: this.listQuery.pageSize,
        // realName:this.listQuery.realName,
        // phoneNumber:this.listQuery.phoneNumber
        status: this.listQuery.status,
        pubAddr: 'job'
      }
      getListPage(params).then(response => {
        this.list = response.data.content
        console.log(this.list)
        this.total = response.data.totalElements
        console.log(this.total)
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 800)
      })
    },
    getAllPub(){
      var params={
        pageNum:0,
        pageSize:100000
      }
      getPubList(params).then(res=>{
        this.sample=res.data.content
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined
      }
    },
    handleChange(row){
      this.rowId=row.id
        updateStatus(this.rowId).then(res=>{
          this.$notify({
            title: '成功',
            message: '上架成功',
            type: 'success',
            duration: 2000
          })
          this.reload()
        })
    },
    handleChange1(row){
      this.rowId=row.id
        updateUp(this.rowId).then(res=>{
          this.$notify({
            title: '成功',
            message: '上架成功',
            type: 'success',
            duration: 2000
          })
          this.reload()
        })
    },
    handleCreate() {
      this.resetTemp()
      this.getAllPub()
      this.temp.pubAddr='job'
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      console.log(this.dynamicValidateForm3.domains)
      for(var i=0; i<this.dynamicValidateForm3.domains.length;i++){
        this.refId.push(this.dynamicValidateForm3.domains[i].value)
      }
      this.temp.refIds=this.refId
      if(this.radio===1){
        this.temp.pubTime=null
      }else if(this.radio===2){
        var aa=this.temp.pubTime.trim().split(/\s+/)
        this.temp.pubTime=aa[0]+'T'+aa[1]
      }
      this.temp.refType='jobOffersId'
      addBottom(this.temp).then(() => {
        this.list.unshift(this.temp)
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success',
          duration: 2000
        })
        this.reload()
      })

    },
    handledelete(row){
        this.rowId=row.id
        this.$confirm('确定删除？ 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
            delBottom(this.rowId).then(res=>{
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.reload()
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
